package com.example.order.controller;

import com.example.common.core.domain.Result;
import com.example.order.feign.ProductFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

    private final ProductFeignClient productFeignClient;

    @GetMapping("/feign")
    public Result<String> testFeign(@RequestParam(defaultValue = "1") Long productId, 
                                   @RequestParam(defaultValue = "1") Integer quantity) {
        log.info("测试Feign调用，productId: {}, quantity: {}", productId, quantity);
        
        try {
            Result<Boolean> result = productFeignClient.decreaseStock(productId, quantity);
            log.info("Feign调用结果: {}", result);
            return Result.success("调用成功: " + result.getMessage());
        } catch (Exception e) {
            log.error("Feign调用异常", e);
            return Result.error("调用异常: " + e.getMessage());
        }
    }

    @GetMapping("/feign-fallback")
    public Result<String> testFeignFallback() {
        log.info("测试Feign Fallback");
        
        // 连续调用多次，触发熔断器
        for (int i = 0; i < 3; i++) {
            try {
                Result<Boolean> result = productFeignClient.decreaseStock(1L, 1);
                log.info("第{}次调用结果: {}", i + 1, result);
            } catch (Exception e) {
                log.error("第{}次调用异常: {}", i + 1, e.getMessage());
            }
        }
        
        return Result.success("Fallback测试完成，请查看日志");
    }

    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("order-service is running");
    }
} 